#region Copyright (c) 2006-2011 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2011 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion

using System;
using System.Linq;
using System.Text;
using Widgetsphere.Generator.Models;

namespace Widgetsphere.Generator.DAL.ProjectItemGenerators.BusinessObjectExtension
{
	public class BusinessObjectExtensionGeneratedTemplate : DomainProjectTemplate
	{
		private readonly StringBuilder sb = new StringBuilder();

		public BusinessObjectExtensionGeneratedTemplate(ModelRoot model)
		{
			_model = model;
		}

		#region BaseClassTemplate overrides
		public override string FileName
		{
			get { return "Extensions.Generated.cs"; }
		}

		public string ParentItemName
		{
			get { return "Extensions.cs"; }
		}

		public override string FileContent
		{
			get
			{
				GenerateContent();
				return sb.ToString();
			}
		}
		#endregion

		#region GenerateContent

		private void GenerateContent()
		{
			try
			{
				Widgetsphere.Generator.GenerationHelper.AppendCopyrightInCode(sb, _model);
				this.AppendUsingStatements();
				sb.AppendLine("namespace " + this.GetLocalNamespace());
				sb.AppendLine("{");
				this.AppendClass();
				sb.AppendLine("}");
			}
			catch (Exception ex)
			{
				throw;
			}
		}

		#endregion

		#region namespace / objects

		public void AppendUsingStatements()
		{
			sb.AppendLine("using System;");
			sb.AppendLine("using System.Linq;");
			sb.AppendLine();
		}

		private void AppendClass()
		{
			try
			{
				sb.AppendLine("	/// <summary>");
				sb.AppendLine("	/// A class that holds extension methods");
				sb.AppendLine("	/// </summary>");
				sb.AppendLine("	public static partial class Extensions");
				sb.AppendLine("	{");
				sb.AppendLine();
				
				#region Business Object Extensions
				foreach (var table in _model.Database.Tables.Where(x => x.Generated && !x.Immutable && !x.AssociativeTable).OrderBy(x => x.Name))
				{
					sb.AppendLine("		/// <summary>");
					sb.AppendLine("		/// Assigns a value to a field on this object.");
					sb.AppendLine("		/// </summary>");
					sb.AppendLine("		/// <param name=\"item\">The entity to set</param>");
					sb.AppendLine("		/// <param name=\"selector\">The field on the entity to set</param>");
					sb.AppendLine("		/// <param name=\"newValue\">The new value to assign to the field</param>");
					sb.AppendLine("		public static void SetValue<TResult>(this " + this.GetLocalNamespace() + ".Business.Objects." + table.PascalName + " item, System.Linq.Expressions.Expression<System.Func<" + this.GetLocalNamespace() + ".Business.Objects." + table.PascalName + ", TResult>> selector, TResult newValue)");
					sb.AppendLine("		{");
					sb.AppendLine("			SetValue(item, selector, newValue, false);");
					sb.AppendLine("		}");
					sb.AppendLine();

					sb.AppendLine("		/// <summary>");
					sb.AppendLine("		/// Assigns a value to a field on this object.");
					sb.AppendLine("		/// </summary>");
					sb.AppendLine("		/// <param name=\"item\">The entity to set</param>");
					sb.AppendLine("		/// <param name=\"selector\">The field on the entity to set</param>");
					sb.AppendLine("		/// <param name=\"newValue\">The new value to assign to the field</param>");
					sb.AppendLine("		/// <param name=\"fixLength\">Determines if the length should be truncated if too long. When false, an error will be raised if data is too large to be assigned to the field.</param>");
					sb.AppendLine("		public static void SetValue<TResult>(this " + this.GetLocalNamespace() + ".Business.Objects." + table.PascalName + " item, System.Linq.Expressions.Expression<System.Func<" + this.GetLocalNamespace() + ".Business.Objects." + table.PascalName + ", TResult>> selector, TResult newValue, bool fixLength)");
					sb.AppendLine("		{");
					sb.AppendLine("			var b = selector.Body.ToString();");
					sb.AppendLine("			var arr = b.Split('.');");
					sb.AppendLine("			if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");");
					sb.AppendLine("			var tn = arr.Last();");
					sb.AppendLine("			var te = (" + this.GetLocalNamespace() + ".Business.Objects." + table.PascalName + ".FieldNameConstants)Enum.Parse(typeof(" + this.GetLocalNamespace() + ".Business.Objects." + table.PascalName + ".FieldNameConstants), tn, true);");
					sb.AppendLine("			item.SetValue(te, newValue);");
					sb.AppendLine("		}");
					sb.AppendLine();
				}
				#endregion

				#region Random Extensions
				sb.AppendLine("		#region Extensions");
				sb.AppendLine();
				sb.AppendLine("		/// <summary>");
				sb.AppendLine("		/// Determines if the specified relation is in this collection");
				sb.AppendLine("		/// </summary>");
				sb.AppendLine("		/// <param name=\"relationList\">This list of items to check for existence</param>");
				sb.AppendLine("		/// <param name=\"relation\">The relation to check</param>");
				sb.AppendLine("		/// <returns></returns>");
				sb.AppendLine("		public static bool Contains(this System.Data.DataRelationCollection relationList, System.Data.DataRelation relation)");
				sb.AppendLine("		{");
				sb.AppendLine("			foreach (System.Data.DataRelation r in relationList)");
				sb.AppendLine("			{");
				sb.AppendLine("				var matches = 0;");
				sb.AppendLine("				foreach (var c in r.ChildColumns)");
				sb.AppendLine("				{");
				sb.AppendLine("					if (relation.ChildColumns.Contains(c))");
				sb.AppendLine("						matches++;");
				sb.AppendLine("				}");
				sb.AppendLine();
				sb.AppendLine("				foreach (var c in r.ParentColumns)");
				sb.AppendLine("				{");
				sb.AppendLine("					if (relation.ParentColumns.Contains(c))");
				sb.AppendLine("						matches++;");
				sb.AppendLine("				}");
				sb.AppendLine();
				sb.AppendLine("				if (r.ChildColumns.Length == (matches * 2))");
				sb.AppendLine("					return true;");
				sb.AppendLine();
				sb.AppendLine("			}");
				sb.AppendLine("			return false;");
				sb.AppendLine("		}");
				sb.AppendLine();
				sb.AppendLine("		#endregion");
				sb.AppendLine();
				#endregion


				sb.AppendLine("	}");
				sb.AppendLine();

			}
			catch (Exception ex)
			{
				throw;
			}
		}

		#endregion

	}
}